﻿// <copyright file="NewKingsIdQueueDaemon.cs" company="Ecole Normale Supérieure">
// Released under GPLv2
// </copyright>
// <summary>Contains a daemon to keep the queue "NewKingsId" from drying out.</summary>

namespace Sqwarea.Batch
{
    using Lokad.Cloud.ServiceFabric;
    using Lokad.Cloud.Services;
    using Lokad.Cloud.Storage;
    using Sqwarea.Persistence;

    /// <summary>
    /// Scheduled service as a daemon to keep the queue "NewKingsId" from drying out
    /// </summary>
    [ScheduledServiceSettings(
        AutoStart = true, 
        ProcessingTimeoutSeconds = GlobalParameters.NewKingsIdQueueTimeOutSeconds, 
        TriggerInterval = GlobalParameters.NewKingsIdQueueCheckoutIntervalSecond)]
    public class NewKingsIdQueueDaemon : ScheduledService
    {
        /// <summary>
        /// Gets or sets queue provider (given by AutoFac Property Injection)
        /// </summary>
        public IQueueProvider QueueProvider { get; set; }

        /// <summary>
        /// Gets or sets global variables provider (given by AutoFac Property Injection)
        /// </summary>
        public IGlobalVariables GlobalVariables { get; set; }

        /// <summary>
        /// Scheduled run of this method keeps the queue "NewKingsId" at a length greater than the lower bound indicated in GlobalParameters.NewKingsIdQueueLengthLowerBound.
        /// </summary>
        protected override void StartOnSchedule()
        {
            if (this.QueueProvider.GetNewKingsIdQueueLength() < GlobalParameters.NewKingsIdQueueLengthLowerBound)
            {
                // Modify GlobalVariables.NextKingId first to have no double Id.
                this.GlobalVariables.NextKingId += GlobalParameters.NewKingsIdQueueInsertNumber;
                this.QueueProvider.PutNewKingsId(
                    this.GlobalVariables.NextKingId - GlobalParameters.NewKingsIdQueueInsertNumber,
                    GlobalParameters.NewKingsIdQueueInsertNumber);
            }
        }
    }
}
